package com.example.shipload_e.database_dao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.shipload_e.util.SystemDateTools;

import android.annotation.SuppressLint;
import android.database.Cursor;

/**
 * db转换成object的工具类
 * @author mrd-luob
 */
@SuppressLint("DefaultLocale")
public class ClassConvertBean {
	/**
	 * @param cla
	 * @param jobj
	 * @return javaBean
	 */
	public static Object returnPojoBean(Class<?> cla,JSONObject jobj) {
		Object javaBean = null;
		Class<?> obj = null;
		try {
			obj = Class.forName(cla.getName());
			javaBean = obj.newInstance();
			@SuppressWarnings("rawtypes")
			Iterator it = jobj.keys();
			while(it.hasNext()) {
				String key = it.next().toString();
				try {
					String getKey = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
					Method getMethod = obj.getDeclaredMethod(getKey, new Class[]{});
					String setKey = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
					Method setMethod = obj.getDeclaredMethod(setKey, getMethod.getReturnType());
					if(getMethod.getReturnType().equals(java.sql.Timestamp.class)) {
						String times = jobj.getJSONObject(key).getString("time");
						if(null == times || "".equals(times)) {
							setMethod.invoke(javaBean, new Object() {});
						} else {
							setMethod.invoke(javaBean, new Timestamp(Long.parseLong(times)));
						}
					} else if(getMethod.getReturnType().equals(BigDecimal.class)) {
						BigDecimal v = new BigDecimal(jobj.getInt(key));
						setMethod.invoke(javaBean, v);
					} else {
						setMethod.invoke(javaBean, jobj.get(key));
					}
				} catch (Exception e) {
					// System.out
					// .println("returnPojoBean(Class<?> cla,JSONObject jobj)-->returnBean:drop:"
					// + key + "\t" + e.getMessage());
				}
			}
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return javaBean;
	}

	/**
	 * @param cla
	 * @param jobjs
	 * @return List<javaBean>
	 */
	public static List<Object> returnPojoBeans(Class<?> cla,JSONArray jobjs) {
		List<Object> list = new ArrayList<Object>();
		try {
			for(int i = 0;i < jobjs.length();i++) {
				Object javaBean = returnPojoBean(cla, jobjs.getJSONObject(i));
				list.add(javaBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * @param cla
	 * @param cs
	 * @return List<javaBean>
	 */
	public static List<Object> returnPojoBeans(Class<?> cla,Cursor cs) {
		List<Object> list = new ArrayList<Object>();
		try {
			if(null != cs && cs.moveToFirst()) {
				do {
					Object javaBean = returnPojoBean(cla, cs);
					list.add(javaBean);
				} while(cs.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * @param cs
	 * @return List<javaBean>
	 */
	public static JSONArray returnJsonBeans(Cursor cs) {
		JSONArray result = new JSONArray();
		try {
			if(null != cs && cs.moveToFirst()) {
				do {
					JSONObject jobj = returnJsonBean(cs);
					result.put(jobj);
				} while(cs.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param cs
	 * @return javaBean
	 */
	public static JSONObject returnJsonBean(Cursor cs) {
		JSONObject result = new JSONObject();
		try {
			for(String key : cs.getColumnNames()) {
				result.put(key, cs.getString(cs.getColumnIndex(key)));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param cla
	 * @param cs
	 * @return javaBean
	 */
	public static Object returnPojoBean(Class<?> cla,Cursor cs) {
		Object javaBean = null;
		Class<?> obj = null;
		try {
			obj = Class.forName(cla.getName());
			javaBean = obj.newInstance();
			for(String key : cs.getColumnNames()) {
				try {
					String getKey = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
					Method getMethod = obj.getDeclaredMethod(getKey, new Class[]{});
					String setKey = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
					Method setMethod = obj.getDeclaredMethod(setKey, getMethod.getReturnType());
					if(getMethod.getReturnType().equals(java.sql.Timestamp.class)) {
						String times = cs.getString(cs.getColumnIndex(key));
						if(null == times || "".equals(times)) {
							// setMethod.invoke(javaBean, new Object() {});
						} else {
							setMethod.invoke(javaBean, new Timestamp(SystemDateTools
							        .parseString(times, "yyyy-MM-dd HH:mm:ss").getTime()));
						}
					} else if(getMethod.getReturnType().toString().equals("int")) {
						setMethod.invoke(javaBean, cs.getInt(cs.getColumnIndex(key)));
					} else {
						setMethod.invoke(javaBean, cs.getString(cs.getColumnIndex(key)));
					}
				} catch (Exception e) {
					// System.out.println("returnPojoBean(Class<?> cla,Cursor cs)-->returnBean:drop:"
					// + key + "\t" + e.getMessage());
				}
			}
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return javaBean;
	}

	/**
	 * @param javaBean
	 * @return JSONObject
	 */
	public static JSONObject returnJSONObject(Object javaBean) {
		JSONObject result = new JSONObject();
		Class<?> obj = javaBean.getClass();
		Field[] dfs = obj.getDeclaredFields();
		for(Field f : dfs) {
			String key = f.getName();
			try {
				String getKey = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
				Method getMethod = obj.getDeclaredMethod(getKey, new Class[]{});
				String setKey = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
				obj.getDeclaredMethod(setKey, getMethod.getReturnType());
				result.put(key, getMethod.invoke(javaBean, new Object[]{}));
			} catch (NoSuchMethodException e) {
				// System.out.println("returnJSONObject(Object javaBean)-->returnBean:drop:" + key
				// + "\t" + e.getMessage());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static JSONArray returnJSONArray(List<Object> javaBeans) {
		JSONArray result = new JSONArray();
		for(Object object : javaBeans) {
			result.put(returnJSONObject(object));
		}
		return result;
	}
}
